package top.techqi.core.util

import android.os.Looper
import androidx.core.os.HandlerCompat
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit

/** 线程工具类 */
@Suppress("unused")
object ThdUtil {
    private val service by lazy { Executors.newScheduledThreadPool(0) }
    private val handler by lazy { HandlerCompat.createAsync(Looper.getMainLooper()) }

    fun postToWorkThread(runnable: Runnable): Future<*> {
        return service.submit(runnable)
    }

    fun postToWorkThread(runnable: Runnable, delayMillis: Long): Future<*> {
        return service.schedule(runnable, delayMillis, TimeUnit.MILLISECONDS)
    }

    fun postToMainThread(runnable: Runnable) {
        handler.post(runnable)
    }

    fun postToMainThread(runnable: Runnable, delayMillis: Long) {
        handler.postDelayed(runnable, delayMillis)
    }

    fun execOnMainThread(runnable: Runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run()
        } else {
            postToMainThread(runnable)
        }
    }

    fun cancelInMainThread(runnable: Runnable) {
        handler.removeCallbacks(runnable)
    }
}
